package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private AnnouncementApi announcementApi;

    @DubboReference
    private CommentsApi commentsApi;


    /*环信用户ID查询用户详细信息*/
    public UserInfoVo findByHuanXinId(String huanxinId) {
        //通过环信用户ID查询用户信息
        User user = userApi.findByHuanXinId(huanxinId);
        //通过用户ID查询用户详细信息
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //构建vo对象
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo);
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    /*联系人添加*/
    public void addContacts(Long friendId) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //注册好友关系到环信
        Boolean result = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + friendId);
        //注册失败则抛出异常
        if (!result) {
            throw new BusinessException(ErrorResult.error());
        }
        //环信注册成功则将好友关系添加到mongodb数据库(双向)
        friendApi.addContacts(userId, friendId);
    }

    /*联系人列表*/
    public PageResult getContacts(Integer page, Integer pagesize, String keyword) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用api查询好友数据
        List<Friend> list = friendApi.findByUserId(userId, page, pagesize);
        //判断好友列表是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取好友数据集合中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //调用api批量查询好友详细信息
        UserInfo info = new UserInfo();
        //添加关键字信息
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //通过循环构造vo对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if (userInfo != null) {
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        //返回结果
        return new PageResult(page, pagesize, 0l, vos);
    }

    /*公告列表*/
    public PageResult announcements(Integer page, Integer pagesize) {
        List<Announcement> list = announcementApi.findAll(page, pagesize);
        //构造vo对象
        List<AnnouncementVo> vos = new ArrayList<>();
        for (Announcement announcement : list) {
            AnnouncementVo vo = new AnnouncementVo();
            vo.setId(announcement.getId().toString());
            vo.setTitle(announcement.getTitle());
            vo.setDescription(announcement.getDescription());
            vo.setCreateDate(announcement.getCreated().toString());
            vos.add(vo);
        }
        return new PageResult(page, pagesize, 0L, vos);
    }

    /*点赞列表*/
    public PageResult likes(Integer page, Integer pagesize, int commentType) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //调用API查询点赞信息
        List<Comment> list = commentsApi.findById(userId, page, pagesize, commentType);
        //判断是否为空
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取点赞列表里的点赞用户的id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        //查询用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        //构造vo
        List<LikesVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                LikesVo vo = new LikesVo();
                vo.setId(comment.getId().toString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setCreateDate(comment.getCreated().toString());
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0L, vos);
    }

}
